package com.qzimp.fujiancuo.service.impl;

import com.qzimp.fujiancuo.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    // 自定义Minio操作相关异常类
    public class MinioOperationException extends RuntimeException {
        public MinioOperationException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    // 自定义文件上传相关异常类
    public class FileUploadException extends RuntimeException {
        public FileUploadException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    @Autowired
    private MinioClient minioClient;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Override
    public String uploadFile(MultipartFile file) {
        try {
            // 检查存储桶是否存在，不存在则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            // 生成唯一文件名，避免文件名冲突
            String objectName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
            // 将文件上传到Minio存储桶
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            return objectName;
        } catch (IOException | MinioException e) {
            System.out.println(0);
            e.printStackTrace();
            return null;
        } catch (NoSuchAlgorithmException e) {
            System.out.println(1);
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            System.out.println(2);
            throw new RuntimeException(e);
        }
    }

}
